import com.google.common.io.Files
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

import java.nio.charset.StandardCharsets

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "com.sample;"
typeMapping = [
        (~/(?i)int/)                      : "long",
        (~/(?i)float|double|decimal|real/): "double",
        (~/(?i)datetime|timestamp/)       : "java.sql.Timestamp",
        (~/(?i)date/)                     : "java.sql.Date",
        (~/(?i)time/)                     : "java.sql.Time",
        (~/(?i)/)                         : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    def className = javaName(table.getName(), true)
    def fields = calcFields(table)
    //创建服务接口
    new File(dir, "I${className}Service.java").withPrintWriter { out -> generate(out, className, fields, dir) }
    //创建服务实现
    new File(new File("${dir.getAbsolutePath()}/impl"), "${className}ServiceImpl.java").withPrintWriter { out -> generateImpl(out, className, fields, dir) }
}

/**
 * 创建服务实现
 * @param out
 * @param className
 * @param fields
 * @param dir
 */
def generateImpl(out, className, fields, dir) {
    packageName = findImplPackageName(dir)
    if(packageName != "") out.println("package ${packageName};")
    out.println("import org.springframework.stereotype.Service;\n" +
            "import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;\n" +
            "import com.hxkj.ad.mapper.${className}Mapper;\n" +
            "import com.hxkj.ad.domain.${className};\n" +
            "import com.hxkj.ad.service.I${className}Service;\n")
    out.println("@Service")
    out.println("public class ${className}ServiceImpl extends ServiceImpl<${className}Mapper, ${className}> implements I${className}Service {\n" +
            "}")
}

/**
 * 创建服务接口
 * @param out
 * @param className
 * @param fields
 * @param dir
 * @return
 */
def generate(out, className, fields, dir) {
    packageName = findPackageName(dir)
    def domainPackage = findDomainPackageName(dir)
    if(packageName != "") out.println "package $packageName;"
    
    out.println ""
    out.println "import ${domainPackage}.${className};"
    out.println "import com.baomidou.mybatisplus.extension.service.IService;"
    out.println ""
    
    out.println "public interface I${className}Service extends IService<${className}> {"
    out.println "}"
}

def calcFields(table) {
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def spec = Case.LOWER.apply(col.getDataType().getSpecification())
        def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
        fields += [[
                           name : javaName(col.getName(), false),
                           type : typeStr,
                           comment: col.getComment(),
                           annos: ""]]
    }
}

def javaName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

/**
 * 查找domain命名空间
 * 
 * @param dir
 */
def findDomainPackageName(dir) {
    return findPackageName(new File(dir.getParent() + "/domain"))
}

/**
 * 获取实现类packageName
 * @param dir
 * @return
 */
def findImplPackageName(dir) {
    return findPackageName(new File(dir.getAbsolutePath() + "/impl"))
}

/**
 * 查找指定目录现有的命名空间
 *
 * @param dir
 * @return
 */
def findPackageName(dir) {
    if(dir != null && dir.isDirectory()) {
        File[] files = dir.listFiles();
        if(files != null && files.length>0) {
            for (File item:files) {
                if(item.isFile()) {
                    List<String> lines = Files.readLines(item, StandardCharsets.UTF_8);
                    //查找命名空间
                    for (String line: lines) {
                        line = line.trim();
                        if(line.startsWith("package")) {
                            line = line.split(" ")[1];
                            line = line.replace(";", "")
                            line = line.trim();
                            return line;
                        }
                    }
                }
            }
        }
    }
    return ""
}